import React from 'react';
import { inject, observer } from 'mobx-react';
import { Spin, Button, Icon, Modal, Table } from 'antd'
import { WeaBrowser, WeaPopoverHrm, WeaInput, WeaSlideModal, WeaTop, WeaRightMenu ,WeaLocaleProvider} from 'ecCom';
import SearchCondition from '../../public/base/SearchCondition';
import KnowledgeMapEdit from './KnowledgeMapEdit'
const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;


@inject('KnowledgeMapListStore')
@observer
export default class KnowledgeMapList extends React.Component {
    constructor(props) {
        super(props);
        window.develop = '知识地图维护';
        this.state = {
            refeshid: -1,
            heightInit: false,
            _top: 0,
            content: "",
            tableloading: false,
            searchStatus: false,
            height: this.getHeight(),
            pageSize: '',
            topName:  getLabel(27939,"知识地图") + getLabel(320,"维护"),
            isshowleft: true,
            locationkey: new Date().getTime(),
            field: '',
            order: '',
            menu: [
                {
                    key: '0',
                    icon: <i className='icon-coms-search' />,
                    content: getLabel(197,"搜索"),
                    onClick: key => this.advanceSearch(),
                },
                {
                    key: '1',
                    icon: <i className='icon-coms-Reset' />,
                    content: getLabel(27088,"重置"),
                    onClick: key => this.resetSearch(),
                }, {
                    key: '2',
                    icon: <i className='icon-coms-Approval' />,
                    content: getLabel(82,"新建"),
                    onClick: key => this.newKnowledge()
                }
            ],
            columns: [
                {
                    title:  getLabel(27939,"知识地图")+ getLabel(195,"名称"),
                    width: '*',
                    dataIndex: 'name',
                    sorter: true,
                    render: (text, record, index) =>
                        <div style={{ cursor: 'pointer' }} onClick={(e) => this.getClickDetail(e, record, "view")}>{text}</div>
                }, {
                    title: getLabel(882,"创建人"),
                    width: '10%',
                    dataIndex: 'createrName',
                    render: (text, record, index) => <a href='javaScript:void(0)' onClick={e => { openhrm(record.createrId); window.pointerXY(e) }} title={text} >{text}</a>
                }, {
                    title: getLabel(1339,"创建时间"),
                    width: '15%',
                    dataIndex: 'createDate',
                    sorter: true,
                    render: (text, record, index) => <div className="noWrap" title={text}>{text}</div>
                }, {
                    title: getLabel(3002,"最后修改人"),
                    width: '10%',
                    dataIndex: 'updaterName',
                    render: (text, record, index) => <a href='javaScript:void(0)' onClick={e => { openhrm(record.updaterId); window.pointerXY(e) }} title={text} >{text}</a>
                }, {
                    title: getLabel(19521,"最后修改日期"),
                    width: '15%',
                    dataIndex: 'updateDate',
                    sorter: true,
                    render: (text, record, index) => <div className="noWrap" title={text}>{text}</div>
                }, {
                    title: getLabel(104,"操作"),
                    width: '20%',
                    dataIndex: 'rowid',
                    className: 'normalfiled',
                    render: (text, record, index) =>
                        <div className="coustmerStyle">
                            <span className="distribute" onClick={(e) => this.handleMenuClick(e, record, '1')}>编辑</span>
                            <span className="distribute" onClick={(e) => this.handleMenuClick(e, record, '2')}>删除</span>
                            <span className="distribute" onClick={(e) => this.handleMenuClick(e, record, '3')}>进入</span>
                            <span className="distribute" onClick={(e) => this.handleMenuClick(e, record, '4')}>添加菜单</span>
                            <span className="distribute" onClick={(e) => this.handleMenuClick(e, record, '5')}>URL</span>
                        </div>
                }
            ],
        }
    }

    componentWillMount() {//一些初始化请求
        const { KnowledgeMapListStore } = this.props;
        let { columns, menu } = this.state;
        let _this = this;
        KnowledgeMapListStore.getKnowledgeList({
            doback: function (hasRight,hasaddmenu) {
                if(!hasRight){
                    menu = menu.splice(0,2);
                    if(hasaddmenu){
                        columns[5] = {
                            title: getLabel(104,"操作"),
                            width: '20%',
                            dataIndex: 'rowid',
                            className: 'normalfiled',
                            render: (text, record, index) =>
                                <div className="coustmerStyle">
                                    <span className="distribute" onClick={(e) => _this.handleMenuClick(e, record, '3')}>进入</span>
                                    <span className="distribute" onClick={(e) => _this.handleMenuClick(e, record, '4')}>添加菜单</span>
                                    <span className="distribute" onClick={(e) => _this.handleMenuClick(e, record, '5')}>URL</span>
                                </div>
                        };
                    }else{
                        columns[5] = {
                            title: getLabel(104,"操作"),
                            width: '20%',
                            dataIndex: 'rowid',
                            className: 'normalfiled',
                            render: (text, record, index) =>
                                <div className="coustmerStyle">
                                    <span className="distribute" onClick={(e) => _this.handleMenuClick(e, record, '3')}>进入</span>
                                    <span className="distribute" onClick={(e) => _this.handleMenuClick(e, record, '5')}>URL</span>
                                </div>
                        };
                    }
                    _this.setState({ columns: columns ,menu:menu});
                }else {
                    if(!hasaddmenu){
                        columns[5] = {
                        title: getLabel(104,"操作"),
                        width: '20%',
                        dataIndex: 'rowid',
                        className: 'normalfiled',
                        render: (text, record, index) =>
                            <div className="coustmerStyle">
                                <span className="distribute" onClick={(e) => _this.handleMenuClick(e, record, '1')}>编辑</span>
                                <span className="distribute" onClick={(e) => _this.handleMenuClick(e, record, '2')}>删除</span>
                                <span className="distribute" onClick={(e) => _this.handleMenuClick(e, record, '3')}>进入</span>
                                <span className="distribute" onClick={(e) => _this.handleMenuClick(e, record, '5')}>URL</span>
                            </div>
                        }
                    }
                    _this.setState({ columns: columns ,menu:menu});
                }
            }
        });
    }
    componentWillUnmount(){
        this.onCloseSlideModal();
    }
    //点击菜单
    handleMenuClick(e, record, type) {
        const { KnowledgeMapListStore } = this.props;
        let { hasRight,hasaddmenu} = KnowledgeMapListStore;
        let rowid = record.rowid;
        KnowledgeMapListStore.rowid = record.rowid;
        if (!hasRight && (type == '1' || type == '2')) {
            e.stopPropagation();
            e.nativeEvent.stopImmediatePropagation();
            return;
        }
        if (!hasaddmenu && type == '4') {
            e.stopPropagation();
            e.nativeEvent.stopImmediatePropagation();
            return;
        }
        if (type == '1') {//编辑
            this.getClickDetail(e, record, "edit");
        } else if (type == '2') {//删除
            this.doDelete(e, record);
        }else if(type=='3'){//进入
           window.open("/knowledgeMap/data/MainInfo.jsp?mapId="+rowid);
        }else if(type =='4'){//添加菜单
            console.log("111");
           window.open("/wui/engine.html#/portalengine/portalmenu/custommenu");
        }else if(type=='5'){//url
            window.prompt("地址",location.protocol + "//" + location.host + "/knowledgeMap/data/MainInfo.jsp?mapId="+rowid);
        }
    }
    //删除
    doDelete(e, record) {
        const { KnowledgeMapListStore } = this.props;
        let _this = this;
        Modal.confirm({
            title: '确定要删除吗？',
            onOk() {
                KnowledgeMapListStore.operateKnowledge({
                    operation: 'delete', knowledgeId: record.rowid, doback: function (status) {
                        if (status == "1") {
                            KnowledgeMapListStore.getKnowledgeList();
                        }else if (status == "3") {
                            Modal.error({
                                title: '提示',
                                content: '知识点被引用,不能删除!',
                            });
                        }
                    }
                });
            },
            onCancel() {

            },
        });
        e.stopPropagation();
        e.nativeEvent.stopImmediatePropagation();
    }
    onCancelDia(type,value){
       if(type==1){
        const { KnowledgeMapListStore } = this.props;
        let _this = this;
        Modal.confirm({
            title: '确定要删除吗？',
            onOk() {
                KnowledgeMapListStore.operateKnowledge({
                    operation: 'delete', knowledgeId: value, doback: function (status) {
                        if (status == "1") {
                            KnowledgeMapListStore.getKnowledgeList();
                            _this.onCloseSlideModal();
                        }
                    }
                });
            },
            onCancel() {

            },
        });
       }else{
           this.onCloseSlideModal();
       }
    }
    getHeight(header) {
        let h = 0;
        if (header) {
            h = header.clientHeight || 0;
        }
        return window.innerHeight - h;
    }

    getTopHeight(header) {
        let h = 0;
        if (header) {
            h = header.clientHeight || 0;
        }
        return h;
    }

    //知识点名称 创建人 
    onBaseSearchChange(ids, names, datas, type, typeArray) {
        const { KnowledgeMapListStore } = this.props;
        if (typeArray != "") {
            KnowledgeMapListStore[typeArray] = datas;
        }
        KnowledgeMapListStore[type] = ids;
    }

    advanceSearch() {
        const { KnowledgeMapListStore } = this.props;
        this.setState({ searchStatus: true });
        let searchParams = this.pieceSearchParam('', '', 'buttonSearch');
        KnowledgeMapListStore.getKnowledgeList(searchParams);
    }
    //重置
    resetSearch() {
        const { KnowledgeMapListStore } = this.props;
        KnowledgeMapListStore.createrArray = [];
        KnowledgeMapListStore.createrId = "";
        KnowledgeMapListStore.name = "";
        this.setState({ searchStatus: false,pageSize:20 });
    }
    getTabButtonsAd() {
        const { KnowledgeMapListStore } = this.props;
        let { hasRight } = KnowledgeMapListStore;
        let button = [(<Button type="primary" onClick={() => this.advanceSearch()}>{getLabel(197,"搜索")}</Button>),
        (<Button type="ghost" onClick={() => this.resetSearch()}>{getLabel(27088,"重置")}</Button>)
        ];
        return button;
    }
    getLeftItems(refesh) {
        const { KnowledgeMapListStore } = this.props;
        const { name, createrId, createrArray } = KnowledgeMapListStore;
        return [
            { title:  getLabel(27939,"知识地图")+ getLabel(195,"名称"), btn: <WeaInput style={{ width: 250 }} placeholder={ getLabel(27939,"知识地图")+ getLabel(195,"名称")} value={name} onChange={(val) => this.onBaseSearchChange(val, "", "", 'name', "")} /> },
            { title:  getLabel(882,"创建人"), btn: <WeaBrowser placeholder={ getLabel(882,"创建人")} inputStyle={{ width: 250 }} type={17} replaceDatas={createrArray} onChange={(ids, names, datas) => this.onBaseSearchChange(ids, names, datas, "createrId", "createrArray")} isSingle={false}/> },
        ]
    }
    showTotal(total) {
        return `共 ${total} 条`;
    }
    showCurrentChange = (current) => {
        const { KnowledgeMapListStore } = this.props;
        KnowledgeMapListStore.pageNum = current;
        let searchParams = this.pieceSearchParam(current, this.state.pageSize);
        KnowledgeMapListStore.getKnowledgeList(searchParams);
    }
    onShowSizeChange = (current, pageSize) => {
        const { KnowledgeMapListStore } = this.props;
        this.setState({ pageSize: pageSize });
        KnowledgeMapListStore.pageNum = current;
        let searchParams = this.pieceSearchParam(current, pageSize);
        KnowledgeMapListStore.getKnowledgeList(searchParams);
    }
    //返回查询条件
    pieceSearchParam(current, pageSize, type) {
        const { KnowledgeMapListStore } = this.props;
        let searchParams = {};
        if (type == 'buttonSearch') {
            searchParams = {
                name: KnowledgeMapListStore.name,
                createrId: KnowledgeMapListStore.createrId,
                field: this.state.field,
                order: this.state.order
            }
        } else {
            if (this.state.searchStatus) {
                searchParams = {
                    pageNum: current,
                    pageSize: pageSize,
                    name: KnowledgeMapListStore.name,
                    createrId: KnowledgeMapListStore.createrId,
                    field: this.state.field,
                    order: this.state.order
                }
            } else {
                searchParams = {
                    pageNum: current,
                    pageSize: pageSize,
                    field: this.state.field,
                    order: this.state.order
                }
            }
        }
        return searchParams;
    }

    //打开新增页面
    newKnowledge(e) {
        const { KnowledgeMapListStore } = this.props;
        const { _top } = this.state;
        KnowledgeMapListStore.slidevisible = true;
        this.setState({ locationkey: new Date().getTime() });
        this.setState({ content: <KnowledgeMapEdit onCallBackSuccess={(arry) => this.onCallBackSuccess(arry)} onCancelDia={(val,value)=>this.onCancelDia(val,value)} minusHeight={_top} operation='add' /> });
        if (e) {
            e.stopPropagation();
            e.nativeEvent.stopImmediatePropagation();
        }
    }
    //点击名称弹出Detail
    getClickDetail(e, record, type) {
        const { KnowledgeMapListStore } = this.props;
        const { _top } = this.state;
        KnowledgeMapListStore.slidevisible = true;
        let _refeshid = -1;
        if (this.state.refeshid == -1) {
            _refeshid = 0;
        }
        this.setState({ content: <KnowledgeMapEdit knowledgeId={record.rowid} refeshid={_refeshid} onCancelDia={(val,value)=>this.onCancelDia(val,value)} onCallBackSuccess={(arry) => this.onCallBackSuccess(arry)} operation={type} minusHeight={_top} />, refeshid: _refeshid });
        e.stopPropagation();
        e.nativeEvent.stopImmediatePropagation();
    }
    //隐藏detail
    hideDetail(e) {
        const { KnowledgeMapListStore } = this.props;
        if (KnowledgeMapListStore.slidevisible) {
            KnowledgeMapListStore.slidevisible = false;
        }
    }
    //操作完成回调
    onCallBackSuccess(optparams) {
        this.setState({ tableloading: true });
        const { KnowledgeMapListStore } = this.props;
        if (optparams.opttype == 'add') {
            this.onCloseSlideModal();
            KnowledgeMapListStore.getKnowledgeList({});
            this.setState({ tableloading: false });
        }
        if (optparams.opttype == 'edit') {
            let rowid = optparams.rowid;
            let type = optparams.type;
            let value = optparams.value;
            let dataSource = KnowledgeMapListStore.dataSource;
            dataSource.length > 0 && dataSource.map((element, index) => {
                if (element.rowid == rowid) {
                    for (let i = 0; i < type.length; i++) {
                        element[type[i]] = value[i];
                    }
                }
            })
            KnowledgeMapListStore.dataSource = dataSource;
            this.setState({ tableloading: false });
        }
    }

    //关闭侧拉框
    onCloseSlideModal() {
        const { KnowledgeMapListStore } = this.props;
        KnowledgeMapListStore.slidevisible = false;
    }

    // 左右布局按钮点击事件
    leftRightFun(leftShow) {
        this.setState({ isshowleft: leftShow });
    }

    ontableChange = (pagination, filters, sorter) => {
        let { field, order } = this.state;
        if (sorter.field != field || sorter.order != order) {
            const { KnowledgeMapListStore } = this.props;
            let searchParams = this.pieceSearchParam('', '', 'buttonSearch');
            searchParams.field = sorter.field;
            searchParams.order = sorter.order;
            KnowledgeMapListStore.getKnowledgeList(searchParams);
            this.setState({ field: sorter.field, order: sorter.order });
        }
    }


    getDetail() {
        const { KnowledgeMapListStore } = this.props;
        let { height, tableloading, columns } = this.state;
        let { dataSource, itotal, pageNum } = KnowledgeMapListStore;

        return (
            <div className="main-tablist">
                <Table
                    scroll={{ x: window.innerWidth * 0.6, y: height - 220 }}
                    columns={columns}
                    bordered={false}
                    loading={tableloading}
                    className="wea-develop-antd-table"
                    onChange={this.ontableChange}
                    dataSource={dataSource} pagination={{
                        total: itotal,
                        onChange: this.showCurrentChange,
                        showTotal: this.showTotal,
                        defaultPageSize: '20',
                        current: pageNum,
                        showSizeChanger: true,
                        onShowSizeChange: this.onShowSizeChange,
                    }} />
            </div>
        )
    }

    render() {
        const { KnowledgeMapListStore } = this.props;
        const { _top, content, height, locationkey, menu,menu1, topName, heightInit, isshowleft } = this.state;
        const { loading, slidevisible, hasRight } = KnowledgeMapListStore;
        let header = document.getElementsByClassName("e9theme-layout-header")[0];
        if (header && !heightInit) {
            this.setState({ _top: this.getTopHeight(header), height: this.getHeight(header), heightInit: true });
        }
        return (
            <div className="knowledge-knowledgeMap-list">
                <WeaTop
                    title={<span style={{ color: '#333333' }}>{ getLabel(27939,"知识地图")+ getLabel(320,"维护")}</span>}
                    icon={<i className='icon-coms-doc' />}
                    iconBgcolor='#FFB555'
                    buttons={[
                        <Button type='primary' onClick={(e) => this.advanceSearch()} >{getLabel(197,"搜索")}</Button>,
                        hasRight && <Button type='primary' onClick={(e) => this.newKnowledge(e)}>{getLabel(82,"新建")}</Button>
                    ]}
                    showDropIcon={true}
                    dropMenuDatas={menu}
                />
                <WeaRightMenu datas={menu} showUrlItem={false} style={{ height: '100%' }}>
                    <div onClick={(e) => this.hideDetail(e)} style={{ height:height}}>
                        <WeaPopoverHrm />
                        <Spin spinning={loading}>
                            <SearchCondition showSearchAd={"none"} buttonsAd={this.getTabButtonsAd()} leftItems={this.getLeftItems()}
                                locationkey={locationkey} darkHeight={height - 105} scrollHeight={375} />

                            {this.getDetail()}
                        </Spin>
                    </div>
                </WeaRightMenu>
                <WeaSlideModal visible={slidevisible}
                    width={75}
                    height={100}
                    top={_top}
                    direction={'right'}
                    measure={'%'}
                    measureT={'px'}
                    content={(content)}
                    onClose={() => this.onCloseSlideModal()} />
            </div>
        )
    }
};